//
//  AppDelegate.m
//  pa
//
//  Created by HaiJiao Chen on 12-7-18.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "ASIFormDataRequest.h"
#import "XMLObject.h"
#import "nibLoader.h"
#import "LoginServer.h"
#import "LoginView.h"
#import "MainObject.h"
#import "FilePack.h"
#import "MiniPrinterFunctions.h"

#define PI 3.1415926

NSString *const DataSourceChangeNotification = @"DataSourceChangeNotification";

AppDelegate* AppDelegate_sharedInstance = nil;
@implementation AppDelegate
@synthesize uid;
@synthesize token;
@synthesize truckID;
@synthesize cachePath;

@synthesize window;
@synthesize viewController;
@synthesize mainView;

- (void)dealloc
{
    [window release];
    [viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
    viewController.view.backgroundColor = [UIColor blackColor];
    cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] retain];
    AppDelegate_sharedInstance = self;
    //[self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];
//    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
//    self.window.rootViewController = [[[UIViewController alloc] init] autorelease];
//    // Override point for customization after application launch.
//    self.window.backgroundColor = [UIColor whiteColor];
//    [self.window makeKeyAndVisible];

    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:NO];
    self.window.transform = CGAffineTransformRotate(self.window.transform, -PI/2);
    self.window.bounds = CGRectMake(0, 0, 1024, 768);
//
    UIView* temp = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 1024, 748)];
    //temp.transform = CGAffineTransformRotate(self.window.transform, -PI);
    //temp.frame = CGRectMake(0, 20, 1024, 748);
    mainView = temp;
    [self.window addSubview:temp];
    //mainView = viewController.view;

    normalQuene = [[ASINetworkQueue alloc] init];
    [normalQuene setDelegate:self];
    [normalQuene setRequestDidFinishSelector:@selector(requestFinished:)];
    [normalQuene setRequestDidFailSelector:@selector(requestFailed:)];
    normalQuene.shouldCancelAllRequestsOnFailure = NO;
    [normalQuene go];


    UIView* login = [nibLoader load:@"Login" params:nil];
    [mainView addSubview:login];
    [LoginServer sharedInstance];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login) name:LoginSuccessfull object:nil];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}



-(ASIHTTPRequest*)sendHttpRequest:(NSString*)uri params:(NSMutableDictionary*)params delegate:(id<HttpRequestDelegate>)delegate
{
    NSMutableArray* tests = [[[NSMutableArray alloc] initWithCapacity:5] autorelease];
    NSString* api = [NSString stringWithFormat:@"/%@&Language=%@", uri, [FilePack currentlanguage]];
    if ([self.uid length] > 0)
    {
        api = [api stringByAppendingFormat:@"&uid=%@", self.uid];
    }
    if ([self.token length] > 0)
    {
        api = [api stringByAppendingFormat:@"&token=%@", self.token];
    }
    //NSString* api = [NSString stringWithFormat:@"/%@&uid=%@&token=%@&Language=%@", uri, self.uid, self.token, [FilePack currentlanguage]];
    NSURL *url = [NSURL URLWithString:api];
    ASIHTTPRequest* request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:(int)delegate], @"delegate", tests, @"tests", params, @"params", nil];

    
    NSArray* servers = [LoginServer sharedInstance].data;
    for (NSDictionary* dic in servers)
    {
        NSString* server = [dic valueForKey:@"url"];
        NSString* test_api = [NSString stringWithFormat:@"%@/paperlessapi.asmx/serverConnectionCheck?&Language=%@&sAddress=1", server, [FilePack currentlanguage]];

        ASIHTTPRequest* test_request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:test_api]] autorelease];
        test_request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:(int)delegate], @"delegate", server, @"server", tests, @"tests", [NSNumber numberWithBool:YES], @"bTest", request, @"request", params, @"params", nil];
        if ([[dic valueForKey:@"connected"] boolValue])
        {
            [tests insertObject:test_request atIndex:0];
        }
        else
        {
            [tests addObject:test_request];
        }
    }

    for (int i = 0; i < [tests count]; i++)
    {
        [normalQuene addOperation:[tests objectAtIndex:i]];
    }

    return request;
}

-(ASIHTTPRequest*)postHttpRequest:(NSString*)uri body:(NSDictionary*)body params:(NSMutableDictionary*)params delegate:(id<HttpRequestDelegate>)delegate multipart:(BOOL)multipart
{
    NSMutableArray* tests = [[[NSMutableArray alloc] initWithCapacity:5] autorelease];
    uri = [NSString stringWithFormat:@"/%@", uri];
    NSURL *url = [NSURL URLWithString:uri];
    ASIFormDataRequest* request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
    for (NSString *key in body.allKeys) {
        id value = [body valueForKey:key];
        if ([value isKindOfClass:[UIImage class]])
        {
            UIImage *image = value;
            [request addData:UIImageJPEGRepresentation(image, 1.0) withFileName:key andContentType:@"image/jpeg" forKey:key];
        }
        else if ([value isKindOfClass:[NSString class]])
        {
            [request addPostValue:value forKey:key];
        }
        else
        {
            value = [NSString stringWithFormat:@"%@", value];
            [request addPostValue:value forKey:key];
        }
    }
    if ([self.uid length] > 0)
    {
        [request addPostValue:self.uid forKey:@"uid"];
    }
    if ([self.token length] > 0)
    {
        [request addPostValue:self.token forKey:@"token"];
    }
    [request addPostValue:[FilePack currentlanguage] forKey:@"Language"];

    request.postFormat = multipart?ASIMultipartFormDataPostFormat:ASIURLEncodedPostFormat;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:(int)delegate], @"delegate", tests, @"tests", params, @"params", nil];
    
    
    NSArray* servers = [LoginServer sharedInstance].data;
    for (NSDictionary* dic in servers)
    {
        NSString* server = [dic valueForKey:@"url"];
        NSString* test_api = [NSString stringWithFormat:@"%@/paperlessapi.asmx/serverConnectionCheck?&Language=%@&sAddress=1", server, [FilePack currentlanguage]];
        
        ASIHTTPRequest* test_request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:test_api]] autorelease];
        test_request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:(int)delegate], @"delegate", server, @"server", tests, @"tests", [NSNumber numberWithBool:YES], @"bTest", request, @"request", params, @"params", nil];
        if ([[dic valueForKey:@"connected"] boolValue])
        {
            [tests insertObject:test_request atIndex:0];
        }
        else
        {
            [tests addObject:test_request];
        }
    }
    
    for (int i = 0; i < [tests count]; i++)
    {
        [normalQuene addOperation:[tests objectAtIndex:i]];
    }

    return request;
}

- (void)cancelRequest:(ASIHTTPRequest*)request
{
    [request cancel];
    NSMutableArray* tests = [request.userInfo valueForKey:@"tests"];
    for (ASIHTTPRequest* t in tests)
    {
        [t cancel];
        t.userInfo = nil;
    }
    [tests removeAllObjects];
    request.userInfo = nil;
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSMutableArray* tests = [request.userInfo valueForKey:@"tests"];
    if ([[request.userInfo valueForKey:@"bTest"] boolValue])
    {
        ASIHTTPRequest* api = [[request.userInfo valueForKey:@"request"] retain];
        XMLObject* xml = [XMLObject parse:[request rawResponseData]];
        if ([xml getIntForKey:@"ret" defaultValue:0] == 1)
        {
            for (NSMutableDictionary* dic in [LoginServer sharedInstance].data)
            {
                [dic setValue:[NSNumber numberWithBool:FALSE] forKey:@"connected"];
            }
            NSString* server = [[[request.userInfo valueForKey:@"server"] retain] autorelease];
            NSString* url = [api.url absoluteString];
            for (ASIHTTPRequest* t in tests)
            {
                [t cancel];
                t.userInfo = nil;
            }
            [tests removeAllObjects];
            
            for (NSMutableDictionary* dic in [LoginServer sharedInstance].data)
            {
                if ([server isEqualToString:[dic valueForKey:@"url"]])
                {
                    [dic setValue:[NSNumber numberWithBool:TRUE] forKey:@"connected"];
                }
            }
            
            api.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/paperlessapi.asmx%@", server, url]];
            [normalQuene addOperation:api];
        }        
        else
        {
            [tests removeObject:request];
            if ([tests count] == 0)
            {
                id<HttpRequestDelegate> delegate = (id<HttpRequestDelegate>)[[request.userInfo valueForKey:@"delegate"] intValue];
                [delegate requestFinished:api params:[request.userInfo valueForKey:@"params"] data:nil succ:NO];
            }
            request.userInfo = nil;
        }
        [api release];
    }
    else
    {
        //NSString* tmp = nil;
        //if ([request postBody])
        //{
        //    char* temp = malloc( [[request postBody] length]+1);
        //    memcpy(temp, [[request postBody] bytes], [[request postBody] length]);
        //    temp[[[request postBody] length]] = 0;
        //    tmp = [NSString stringWithUTF8String:temp];
        //    free(temp);
        //}
        XMLObject* xml = [XMLObject parse:[request rawResponseData]];
        id<HttpRequestDelegate> delegate = (id<HttpRequestDelegate>)[[request.userInfo valueForKey:@"delegate"] intValue];
        [delegate requestFinished:request params:[request.userInfo valueForKey:@"params"] data:xml succ:YES];
        request.userInfo = nil;
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    if ([[request.userInfo valueForKey:@"bTest"] boolValue])
    {//测试连接
        NSMutableArray* tests = [request.userInfo valueForKey:@"tests"];
        [tests removeObject:request];
        if ([tests count] == 0)
        {
            id<HttpRequestDelegate> delegate = (id<HttpRequestDelegate>)[[request.userInfo valueForKey:@"delegate"] intValue];
            ASIHTTPRequest* api = [[request.userInfo valueForKey:@"request"] retain];
            [delegate requestFinished:api params:[request.userInfo valueForKey:@"params"] data:nil succ:NO];
            [api release];
        }
        request.userInfo = nil;
    }
    else
    {
        id<HttpRequestDelegate> delegate = (id<HttpRequestDelegate>)[[request.userInfo valueForKey:@"delegate"] intValue];
        [delegate requestFinished:request params:[request.userInfo valueForKey:@"params"] data:nil succ:NO];
        request.userInfo = nil;
    }
}

+ (AppDelegate*)sharedInstance
{
    return AppDelegate_sharedInstance;
}


@synthesize main;
- (void)login
{
    main = [[MainObject alloc] init];
}

- (void)logout
{
    [main release];
    main = nil;
    UIView* login = [nibLoader load:@"Login" params:nil];
    [mainView addSubview:login];
}



static NSString *portName = nil;
static NSString *portSettings = nil;

+ (NSString*)getPortName
{
    return portName;
}

+ (void)setPortName:(NSString *)m_portName
{
    if (portName != m_portName) {
        [portName release];
        portName = [m_portName copy];
    }    
}

+ (NSString *)getPortSettings
{
    return portSettings;
}

+ (void)setPortSettings:(NSString *)m_portSettings
{
    if (portSettings != m_portSettings) {
        [portSettings release];
        portSettings = [m_portSettings copy];
    }
}

+ (NSString *)HTMLCSS
{
    NSString *cssDefninition = @"<html>\
    <head>\
    <style type=\"text/css\">\
    Code {color:blue;}\n\
    CodeDef {color:blue;font-weight:bold}\n\
    TitleBold {font-weight:bold}\n\
    It1 {font-style:italic; font-size:12}\n\
    LargeTitle{font-size:20px}\n\
    SectionHeader{font-size:17;font-weight:bold}\n\
    UnderlineTitle {text-decoration:underline}\n\
    div_cutParam {position:absolute; top:100; left:30; width:200px;font-style:italic;}\n\
    div_cutParam0 {position:absolute; top:130; left:30; font-style:italic;}\n\
    div_cutParam1 {position:absolute; top:145; left:30; font-style:italic;}\n\
    div_cutParam2 {position:absolute; top:160; left:30; font-style:italic;}\n\
    div_cutParam3 {position:absolute; top:175; left:30; font-style:italic;}\n\
    .div-tableBarcodeWidth{display:table;}\n\
    .div-table-rowBarcodeWidth{display:table-row;}\n\
    .div-table-colBarcodeWidthHeader{display:table-cell;border:1px solid #000000;background: #800000;color:#ffffff}\n\
    .div-table-colBarcodeWidthHeader2{display:table-cell;border:1px solid #000000;background: #800000;color:#ffffff}\n\
    .div-table-colBarcodeWidth{display:table-cell;border:1px solid #000000;}\n\
    rightMov {position:absolute; left:30px; font-style:italic;}\n\
    rightMov_NOI {position:absolute; left:55px;}\n\
    rightMov_NOI2 {position:absolute; left:90px;}\n\
    StandardItalic {font-style:italic}\
    .div-tableCut{display:table;}\n\
    .div-table-rowCut{display:table-row;}\n\
    .div-table-colFirstCut{display:table-cell;width:40px}\n\
    .div-table-colCut{display:table-cell;}\n\
    .div-table-colRaster{display:table-cell; border:1px solid #000000;}\n\
    </style>\
    </head>";
    return cssDefninition;
}

@end
